<template>
    <div style="text-align: center;margin: auto">
<!--        <div style="height: 50px">-->
<!--            <el-button type="warning" plain-->
<!--                       @click="" style="float: left">新增</el-button>-->
<!--        </div>-->
        <el-table
            border
                :data="users"
                style="width:1450px;border-radius: 15px">
            <el-table-column
                align="center"
                    label="头像"
                    prop="picSrc" >
                <template slot-scope="scope">
                    <el-image :src="scope.row.picSrc" style="width: 50px;height: 50px" v-if="scope.row.picSrc!==null"/>
                    <span :src="scope.row.picSrc" style="width: 50px;height: 50px" v-if="scope.row.picSrc===null">暂无</span>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                    label="用户名"
                    prop="username" >
            </el-table-column>
            <el-table-column
                align="center"
                    label="姓名"
                    prop="name" >
            </el-table-column>
            <el-table-column
                align="center"
                    label="手机号"
                    prop="phone" >
            </el-table-column>
            <el-table-column
                align="center"
                    label="状态"
                    prop="stat" >
                <template slot-scope="scope">
                    <span v-if="scope.row.stat==='1'">正常</span>
                    <span v-if="scope.row.stat==='0'">冻结</span>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                      label="积分"
                    prop="score" >
            </el-table-column>

            <el-table-column

                    align="center" >
                <template slot="header" slot-scope="scope">
                    <span style="margin-right:10px">操作</span>
                </template>
                <template slot-scope="scope" style="width: 100px">
                    <el-button
                            size="mini"

                            @click="edit(scope.row)" style="background-color: #fced6e;width: 50px;display: inline-block">修改</el-button>
                    <el-button
                            size="mini"
                            type="warning"
                            @click="freeze(scope.row)" style="width: 50px;display: inline-block" v-if="scope.row.stat==='1'">冻结</el-button>
                    <el-button
                            size="mini"
                            type="success"
                            @click="freeze(scope.row)" style="width: 50px;display: inline-block" v-if="scope.row.stat==='0'">开启</el-button>
                </template>
            </el-table-column>
        </el-table>
      <el-dialog title="用户信息" :visible.sync="dialogVisible" style="line-height: 15px">
        <el-form :model="editUserInfo" status-icon :rules="userRules" ref="editUserInfo" style="text-align: left">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="editUserInfo.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-input v-model="editUserInfo.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload
                            ref="upload"
                            action="http://localhost:8084/upload"
                            name="picture"
                            list-type="picture-card"
                            :limit="1"
                            :file-list="fileList"
                            :on-exceed="onExceed"
                            :before-upload="beforeUpload"
                            :before-remove="beforeRemove"
                            :on-preview="handlePreview"
                            :on-success="handleSuccess"
                            :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogPicVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button style="background-color: #fced6e"@click="flush">取 消</el-button>
                <el-button style="background-color: #009be2"type="primary" @click="save">保 存</el-button>
            </span>
      </el-dialog>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    </div>
</template>

<script>
    export default {
        name: "UserManager",
        created() {
            //this.userInfo = this.$route.params.userInfo;
            this.axios.get("http://localhost:8084/findAllUserByPage",{
                params:{
                    currentPage:this.currentPage,
                    pageSize:this.pageSize
                }
            }).then(resp=>{
                console.log(resp.data);
                this.users = resp.data.users;
                this.total = resp.data.count;
            })
        },
        data(){
          /*店铺信息非空判断和唯一验证*/
          const validateUsername = (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入用户名'));
            } else {
              callback();
            }
          };
          const validatePassword = (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入密码'));
            } else {
              callback();
            }
          };
            return{
                userInfo:'',
                fileList:[],
                search:'',
                users:[
                    {
                        id:"",
                        username:'123',
                        name:'',
                        phone:'',
                        picSrc:'',
                        score:'',
                        stat:''
                    }
                ],

                pageSize:5,
                total: 0,
                currentPage: 1,
                pageSizes:[1,2,3,4,5,6,7,8,9,10],

              editUserInfo:{
                id:'',
                username:'',
                password:'',
                picSrc:'',
              },
              userRules:{
                username:[
                  { validator:validateUsername,trigger: 'blur'}
                ],
                password: [
                  { validator:validatePassword,trigger: 'blur'}
                ],
              },
              formLabelWidth: '120px',


              dialogVisible: false,
            }
        },
        methods:{
            handleSizeChange(val) {
                this.pageSize = val;
                const that = this;
                this.axios.get("http://localhost:8084/findAllUserByPage",{
                    params:{
                        currentPage:this.currentPage,
                        pageSize:this.pageSize
                    }
                }).then(resp=>{
                    console.log(resp.data);
                    this.users = resp.data.users;
                    this.total = resp.data.count;
                })
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                const that = this;
                this.axios.get("http://localhost:8084/findAllUserByPage",{
                    params:{
                        currentPage:this.currentPage,
                        pageSize:this.pageSize
                    }
                }).then(resp=>{
                    console.log(resp.data);
                    this.users = resp.data.users;
                    this.total = resp.data.count;
                })
            },
            /*取消保存*/
        flush(){
                this.dialogVisible = false;
                this.$router.push({
                    name:"blank",
                    params:{
                        url:"userManager"
                    }
                })
            },
          edit(item){
            console.log(item);
            this.dialogVisible = true;
            this.editUserInfo.id = item.id;
            this.editUserInfo.username = item.username;
            this.editUserInfo.password = item.password;
            this.editUserInfo.picSrc = item.picSrc;
            this.fileList.push({
                    'url': item.picSrc
                })
          },
          /*保存修改*/
        save() {
                console.log(this.editUserInfo);
                this.$refs['editUserInfo'].validate((valid) => {
                    if (valid) {
                        this.$confirm("确定要保存修改吗？", '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'info'
                        }).then(() => {
                            this.axios.post("http://localhost:8084/updateUserMessage", this.editUserInfo).then(resp => {
                                if (resp.data === "success") {
                                    this.$message({
                                        message: "保存成功！！！",
                                        type: 'success'
                                    });
                                    this.flush();
                                } else {
                                    this.$message({
                                        message: "保存失败！！！",
                                        type: 'warning'
                                    });
                                    this.flush();
                                }
                            })
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消'
                            });
                        })
                    } else {
                        return false;
                    }
                })
            },
          freeze(row){
                console.log(row);
                var msg='冻结';
                var statTemp='0';//默认正常
                if(row.stat==='0'){//冻结状态改成正常
                  statTemp='1';
                  msg='开启';
                }
                this.$confirm("确定要"+msg+"这个用户吗？",'提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type:'warning'
                 }).then(()=>{
                    this.axios.get("http://localhost:8084/changeUserStat",{
                    params:{
                      stat:statTemp,
                      id:row.id
                    }
                }).then(resp=>{
                    if(resp.data === "success"){
                        this.$message({
                        message:msg+"成功！！！",
                        type:'success'
                        });
                    }else{
                        this.$message({
                        message:msg+"失败！！！",
                        type:'warning'
                        });
                    }
                      this.flush();
                })
            })
        }
        ,
            //文件上传成功的钩子函数
            handleSuccess(res, file) {
                this.$message({
                    type: 'info',
                    message: '图片上传成功',
                    duration: 6000
                });
                console.log(file);
                if (file.response.code===200) {
                    this.editUserInfo.picSrc = file.response.message; //将返回的文件储存路径赋值picture字段
                }
            },

            handleSuccessAdd(res, file) {
                this.$message({
                    type: 'info',
                    message: '图片上传成功',
                    duration: 6000
                });
                console.log(file);
                if (file.response.code===200) {
                    this.editUserInfo.picSrc = file.response.message; //将返回的文件储存路径赋值picture字段
                }
            },

            //删除文件之前的钩子函数
            handleRemove(file, fileList) {
                this.$message({
                    type: 'info',
                    message: '已删除原有图片',
                    duration: 6000
                });
            },
            //图片预览
            handlePreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },


            //上传的文件个数超出设定时触发的函数
            onExceed(files, fileList) {
                this.$message({
                    type: 'info',
                    message: '最多只能上传一个图片',
                    duration: 6000
                });
            },

            //文件上传前的前的钩子函数
            //参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
            beforeUpload(file){
                const isJPG = file.type === 'image/jpeg';
                const isGIF = file.type === 'image/gif';
                const isPNG = file.type === 'image/png';
                const isBMP = file.type === 'image/bmp';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG && !isGIF && !isPNG && !isBMP) {
                    this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
            },

            //删除前提示
            beforeRemove(file) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            }
        }
    }
</script>

<style scoped>
    .el-table{
        line-height: 50px;
        margin: auto;
    }
</style>
